package com.lich.filter;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.lich.entity.AccessLog;
import com.lich.service.AccessLogService;
import com.lich.service.AccessManagerService;
import com.lich.util.DateUtils;

/**
 * @description 限制访问过次数
 * @author hgk
 * @date 2016年9月18日
 */
public class LimitInterceptor extends BaseInterceptor implements HandlerInterceptor {
	
	/**
	 * 目标地址
	 */
	
	private String redirect;
	
	@Resource
	private AccessLogService accessLogService;
	@Resource
	private AccessManagerService accessManagerService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		String uri = request.getRequestURI();
		String ip = getIpAddr(request);
		long accessTimes = accessLogService.getIPCount(ip, DateUtils.addHours(new Date(), -1), new Date(),uri);
		Integer limitTimes = accessManagerService.selectByUrl(uri);
		AccessLog accessLog = new AccessLog();
		accessLog.setAccessIp(ip);
		accessLog.setAccessTime(new Date());
		accessLog.setSessionId(request.getRequestedSessionId());
		accessLog.setUrl(uri);
		if (limitTimes==null) {
			return true;
		}
		if (accessTimes>=limitTimes) {
			accessLog.setFlag(false);
			accessLogService.save(accessLog);
			return false;
		}
		accessLog.setFlag(true);
		accessLogService.save(accessLog);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if(modelAndView != null){
			String basePath = request.getContextPath();
			modelAndView.addObject("basePath", basePath);
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	public String getRedirect() {
		return redirect;
	}

	public void setRedirect(String redirect) {
		this.redirect = redirect;
	}
	
	
	
}
